# from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from seleniumwire import webdriver
import os,time
import hashlib,sys
import json
import time
import math
import requests
import datetime
from docxtpl import DocxTemplate
import config
import pandas as pd
import warnings
# 创建获取token函数，token函数是加密后的数据
def md5(data,Authorization):
    data = '{}?61b44513-3d63-47a7-a54f-b8d9f0da4165_Wake_Token_{}'.format(data,Authorization)
    # print(data)
    pa = hashlib.md5(data.encode()).hexdigest()
    return pa
# 通过模拟登录获取指定数据
def json_value(page,allSearch,Authorization):
    # payload = "{\"pageNum\":" + f"{page}" + ",\"pageSize\":200,\"orderKey\":\"created_at\",\"orderType\":\"desc\",\"allSearch\":\"张佶\",\"categoryId\":0,\"ids\":\"\",\"groupId\":0,\"placeId\":0,\"scrapAsset\":0,\"isSelf\":0,\"realCategory\":0}"
    payload = "{\"pageNum\":" + f"{page}" + ",\"pageSize\":200,\"orderKey\":\"created_at\",\"orderType\":\"desc\",\"allSearch\":" + f"\"{allSearch}\"" + ",\"categoryId\":0,\"ids\":\"\",\"groupId\":0,\"placeId\":0,\"scrapAsset\":0,\"isSelf\":0,\"realCategory\":0}"
    data = json.dumps(json.loads(payload), ensure_ascii=False).replace(' ', '')
    token = md5(data,Authorization)
    url = "https://center.wakethings.com/api/asset/asset/assetList"
    headers = {
        'Host': 'center.wakethings.com',
        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
        'sec-ch-ua-mobile': '?0',
        'Authorization': 'bearer {}'.format(Authorization),
        'Content-Type': 'application/json;charset=UTF-8',
        'Accept': 'application/json, text/plain, */*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        'Wkt-Token': token,
        'sec-ch-ua-platform': '"Windows"',
        'Origin': 'https://center.wakethings.com',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://center.wakethings.com/',
        'Accept-Language': 'zh-CN,zh;q=0.9'
    }
    response = requests.request("POST", url, headers=headers, data=payload.encode('utf-8'))
    return response.json()
# 将获取的数据做处理，处理过滤剩下自己需要的数据结构
def cycle(page,allSearch,Authorization):
    response = json_value(page,allSearch,Authorization)
    # print(response)
    total = math.ceil(response.get('data').get('total') / 200)
    # print(total)
    for page in range(2, total+1):
        # response = req(page)
        response = page
    a = response["data"]["rows"]
    list1 = []
    for data in a:
        statusName = data["statusName"]
        usepeoper = data["usepeoper"]
        if statusName == '使用中' and usepeoper == allSearch:
            # a = str("使用状态：") + (data["statusName"])
            # b = str("使用人：") + (data["usepeoper"])
            # c = str("资产GZ编码") + (data["assetId"])
            # d = str("资产S/N号") + (data["S/N"])
            a = data["statusName"]
            b = data["usepeoper"]
            c = data["assetId"]
            d = data["S/N"]
            e = {"使用状态":a,"使用人":b,"资产GZ编码":c,"资产S/N号":d}
            # print(e)
            list1.append(e)
            # print(list1)
    return list1
# 将处理后的数据再次处理，并将指定值传入到word模板中
def excel_w(page,allSearch):
    doc = DocxTemplate("/Users/weidian/Desktop/assets.docx")  # 选定模板
    data = cycle(page,allSearch,Authorization)
    # print(data)
    for value in data:
        # print(value)
        name = value["使用人"]
        GZ = value["资产GZ编码"]
        SN = value["资产S/N号"]
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        context = {'name': name,
                    'gz': GZ,
                    'sn': SN,
                    'date': date
                    }  # 需要替换的内容
        # print(context)
        doc.render(context)  # 渲染替换
        doc.save(name + GZ + "资产转移表.docx")  # 保存
# windows 与 linux 通用脚本，在Unix OS（OSX，Linux等）上，隐藏文件以“。”开头。因此我们可以使用简单的startwith check过滤掉它们。在Windows上，我们需要检查文件属性，然后确定文件是否隐藏。
def file_is_hidden(p):
    # 如果是Windows的话则需要导入以下包，并通过检查文件属性来确认文件是否隐藏
    if os.name == "nt":
        import win32api, win32con
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    # 否则就是Linux，不需要导入其他包，通过.开头来过滤
    else:
        return p.startswith('.')  # linux-osx
# 查找指定目录下xls，xlsx文件
def find_file(file_path,file_ext):
    for path in os.listdir(file_path):
        if not file_is_hidden(path):
            path_list = os.path.join(file_path, path)  # 连接当前目录及文件或文件夹名称
            if os.path.isfile(path_list):  # 判断当前文件或文件夹是否是文件，把文件夹排除
                if (os.path.splitext(path_list)[1]) in file_ext:  # 判断取得文件的扩展名是否是.xls、.xlsx
                    return path_list  # 打印输出
# 获取需要查询的名单
def get_name(path):
    # a = sys.argv[1]
    namelist = []
    df = pd.read_excel(path,header=1)  # 这个会直接默认读取到这个Excel的第一个表单
    # print(df)
    for i in (df["姓名"].values):
        namelist.append(i)
    return namelist
# 通过上方查询到的名单循环调用上方写的函数
def start_action(allSearchlist):
    try:
        for start in allSearchlist:
            # print(start)
            excel_w(1,start)
    except:
        print("程序异常，请确认代码路径、token是否正常，一般Authorization有效期只有一天。")

## 查找元素 by class
def find_element_by_class(driver, class_name):
    return WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.CLASS_NAME, class_name)), '未找到 Class 为 "%s" 的元素' % class_name)

## 查找元素 by class all

def find_element_by_class_all(driver, class_name):
    # print(WebDriverWait(driver, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, class_name))),'未找到 Class 为 "%s" 的元素' % class_name)
    return WebDriverWait(driver, delay).until(EC.presence_of_all_elements_located((By.CLASS_NAME, class_name)), '未找到 Class 为 "%s" 的元素' % class_name)
## 查找元素 by id
def find_element_by_id(driver, id):
    # print(WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, id))),'未找到 id 为 "%s" 的元素' % id)
    return WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, id)), '未找到 id 为 "%s" 的元素' % id)
## 查找元素并且是可用状态 by class
def find_enable_by_class(driver, class_name):
    return WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CLASS_NAME, class_name)), '元素 "%s" 不可用' % class_name)

## 查找元素 by css
def find_element_by_css(driver, css):
    return WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css)), 'css元素 "%s" 不可用' % css)

def authorization(user,password):
    # 定位输入框
    user_input = find_element_by_class(driver, 'ivu-input-large')
    # 在输入框输入值
    user_input.send_keys(user)
    # 定位输入框
    pass_input = find_element_by_class(driver,'ivu-input-with-suffix')
    # 在输入框输入值
    pass_input.send_keys(password)
    # 这是定位元素后并且模拟点击，我这里是登录按钮，输入了账号密码后就是点击登录
    find_enable_by_class(driver,'ivu-btn-large').click()
    # 等待
    time.sleep(1)
    # 定义一个url
    token_url = "https://center.wakethings.com/api/configuration/set/generalTypeList"
    # 循环读取 登录后的请求url
    for i in driver.requests:
        if i.url == token_url:
            token = i.headers.get("Authorization").split(' ')[1]
            # print(token)
            return token
    time.sleep(1)
    driver.quit()
if __name__ == '__main__':
    #忽略告警
    warnings.filterwarnings('ignore')
    chromedriver = '/Users/weidian/appleidauto/appleid/venv/bin/chromedriver'  # 驱动所在路径
    # 传入webdriver驱动，谷歌家在驱动
    service = Service(chromedriver)
    os.environ["webdriver.chrome.driver"] = chromedriver
    # 配置默认选项，谷歌启动的时候加载
    user_ag = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36"
    options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
    options.add_argument('window-size=1920x1080')  # 指定浏览器分辨率
    options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
    options.add_argument('--headless')  # 隐藏谷歌浏览器，一般我们不需要显示可视化的话就需要加这个参数
    options.add_argument('user-agent=%s' % user_ag)
    driver = webdriver.Chrome(service=service, options=options)
    # 需要访问的网站地址，类似我们平常流程输入的地址一样
    driver.get("https://center.wakethings.com/#/asset/asset_query")
    # 设定默认的延迟时间，下面定位会用到
    delay = 5
    # 写好默认的元素，id定位函数，为后面写逻辑代码做准备
    #这是认证钥匙，token基于此字段值做加密的，如果无法模拟登录了那么则需要重新获取替换一下这个值
    # Authorization=config.Conf['SECRET']
    Authorization = authorization("19323032087","Fuck38!!")
    #名单路径
    path_init = config.Conf['PATH']
    file_ext = ['.xls', '.xlsx']
    #通过拼接获取入职名单完整表格
    # path = path_init + sys.argv[1] + str(".xlsx")
    path = find_file(path_init, file_ext)
    # print(path)
    allSearchlist= get_name(path)
    start_action(allSearchlist)